package com.superc.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.superc.client.HttpProxyService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;


@SuppressWarnings("serial")
public class HttpProxyServiceImpl extends RemoteServiceServlet implements HttpProxyService {

	@Override
	public String query(String url, String method, String postData)
			throws IllegalArgumentException {
		HttpURLConnection connection=null;
		String message=null;
		try {
			connection= (HttpURLConnection) new URL(url).openConnection();
			connection.setRequestMethod(method);
			if(postData!=null&&postData.length()>0){
				OutputStream out=connection.getOutputStream();
				out.write(postData.getBytes());
				out.flush();
				out.close();
			}
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader in = null; 
		        try { 
		          in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		          String inputLine; 
		          StringBuffer tempHtml=new StringBuffer();
		          while ( 
		            (inputLine = in.readLine()) != null) { 
		        	  tempHtml.append(inputLine);
		          } 
		          message=tempHtml.toString();
		        } catch (IOException e) { 
		          e.printStackTrace(); 
		        } 

            } else {
                message="";
            }
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally{
			if(connection!=null){
				connection.disconnect();
			}
		}
		return message;
	}

	
}
